package com.xk.ucs.modbus.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Objects;
import java.util.Properties;

/**
 * Date:2021/1/18
 * Author：01398017
 * Description: modbus加载属性配置文件类
 **/
@Slf4j
@Configuration
@ConditionalOnProperty(name = "modbus.init",havingValue = "true")
public class ModBusProperties {
    private static  Properties properties  = new Properties();
    @Value("${modbus.host}")
    private String host;
    @Value("${modbus.port}")
    private  int port;
    private  int slaveId;
    static {
        // 优先取config文件夹里的配置，如果没有，就取项目里的配置
        InputStream inputStream1 = null;
        InputStream inputStream2 = null;
        String path = System.getProperty("user.dir")+File.separator+"config"+File.separator+ "modbusVRConfig.properties";
        try{
            inputStream1 = new FileInputStream(new File(path));
        } catch (Exception e){
            inputStream2 = ModBusProperties.class.getResourceAsStream("/modbusVRConfig.properties");
        }
        try {
            log.info("modbus配置地址{}",path);
            log.info("modbus读取{}配置", inputStream1 == null ? "jar包" : "外部");
            properties.load(inputStream1 != null ? inputStream1 : inputStream2);
        }catch (Exception e) {
            log.error("加载modbus配置文件出错", e);
        }
    }

    @PostConstruct
    public  void init(){
        this.slaveId=Integer.parseInt((String)  properties.get("slaveId"));
        Objects.requireNonNull(this.host);
        Objects.requireNonNull(this.port);
    }
    public  static  Properties getProperties(){
        return properties;
    }

    public String getHost() {
        return this.host;
    }


    public int getPort() {
        return this.port;
    }

    public int getSlaveId() {
        return slaveId;
    }

    public void setSlaveId(int slaveId) {
        this.slaveId = slaveId;
    }
}
